package com.briup.security.config;

import com.briup.security.ImageCodeFilter;
import com.briup.security.util.ImageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.awt.*;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("myDetailService")
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public ImageCodeFilter imageCodeFilter() {
        return new ImageCodeFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.formLogin() // 表示使用表单进行登录
                .loginPage("/login.html") // 表示登录界面地址
                .loginProcessingUrl("/user/login") //表单登录地址
                .defaultSuccessUrl("/test/hello") // 登录成功跳转地址
                .and()  // 拼接 条件
                .authorizeRequests() // 设置需要认证的请求地址
                .antMatchers("/image/code","/","/login.html","/user/login").permitAll() // 设置 不需要认证的请求
                .anyRequest().authenticated() // 任何请求都需要认证
                .and()
                .csrf().disable(); // 关闭 security 的 csrf防护
        // 添加验证码过滤器到用户名密码过滤器之前
        http.addFilterBefore(imageCodeFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 设置认证逻辑为用户自定义认证逻辑
         * 设置密码加密处理器为 BCryptPasswordEncoder
         */
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }
}
